package com.ebeitech.doorapp.application;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import com.ebeitech.doorapp.constants.CommonConstants;
import com.ebeitech.doorapp.db.CommonDBHelper;
import com.ebeitech.doorapp.domain.dao.UserDao;
import com.ebeitech.doorapp.push.xiaomi.PushUtils;
import com.ebeitech.doorapp.qqim.util.QQIMUtil;
import com.ebeitech.library.ui.dialog.DialogActivity;
import com.ebeitech.library.util.Log;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.doorapp.domain.User;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.SPManager;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.qcloud.presentation.business.InitBusiness;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.ArrayList;
import java.util.List;
//import com.ebeitech.com.ebeitech.library.util.StringUtil;
//import com.ebeitech.com.ebeitech.library.util.ThreadFactory;
//import com.netease.nis.bugrpt.CrashHandler;
//import com.netease.nis.bugrpt.user.UserStrategy;
//import com.xiaomi.channel.commonutils.logger.LoggerInterface;
//import com.xiaomi.mipush.sdk.Logger;

/**
 * Created by alice on 2017/10/24.
 */

public class EbeiApplication extends Application {

    private static Context context;
    private static List<Activity> mActivitys = new ArrayList<Activity>();
    /**
     * 登陆用户
     */
    private static User mUser;
    /**
     * 登陆用户名 ，数据库名
     */
    private static String mUserAccount;

    /**
     * Application 实例
     */
    private static EbeiApplication cipApplication;

    @Override
    public void onCreate() {
        super.onCreate();
        this.context = this;
        cipApplication = this;
        mUser = new User();
        mUserAccount = SPManager.getInstance(this).get(SPConstants.USER_ACCOUNT,"");
        initData();

        //本地异常捕捉
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());

        // 初始化腾讯云
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        int loglvl = pref.getInt("loglvl", TIMLogLevel.DEBUG.ordinal());
        //初始化IMSDK
        InitBusiness.start(getApplicationContext(),loglvl);
        //初始化TLS
//        TlsBusiness.init(getApplicationContext());

//        ThreadFactory.builder();

        //网易云捕
//        UserStrategy strategy = new UserStrategy(getApplicationContext());
//        strategy.setUserId(getUser().getUserName());
//        strategy.setUserTag("ebei");
//        strategy.setVersionSuffix("ebei");
//        CrashHandler.init(getApplicationContext(),strategy);

//        LoggerInterface newLogger =new LoggerInterface() {
//            @Override
//            public void setTag(String s) {
//
//            }
//
//            @Override
//            public void log(String s) {
//                Log.d("xiaomi", s);
//            }
//
//            @Override
//            public void log(String s, Throwable t) {
//
//                Log.d("xiaomi", s, t);
//            }
//        };


        SPManager.getInstance(context).put(SPConstants.SHARED_PRE_CHANNEL_ID_KEY, "");
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks);
    }

    public EbeiApplication getCipApplication() {
        return cipApplication;
    }

    public static Context getContext() {
        return context;
    }

    /**
     * 获取登陆用户
     * @return
     */
    public static User getUser() {
        if(mUser == null || StringUtil.isStringNullOrEmpty(mUser.getUserAccount())){
            User user = UserDao.getInstance().getUserByAccount(SPManager.getInstance(context).get(SPConstants.USER_ACCOUNT,""));
            if(user != null && !StringUtil.isStringNullOrEmpty(user.getUserAccount())){
                setUser(user);
            }
        }
        return mUser;
    }

    /**
     * 设置登陆用户
     * 设置数据库
     * @param user
     */
    public static void  setUser(User user) {
        mUser = user;
        mUserAccount = user.getUserAccount();

        SPManager.getInstance(context).put(SPConstants.USER_ACCOUNT,user.getUserAccount());
        SPManager.getInstance(context).put(SPConstants.USER_ID,user.getUserId());
        SPManager.getInstance(context).put(SPConstants.USER_NAME,user.getUserName());
        SPManager.getInstance(context).put(SPConstants.USER_SIG,user.getUserSig());

        CommonDBHelper.changeDBHelper(mUserAccount);
    }

    public static String getUserAccount() {
        return mUserAccount;
    }

	/**
     * 初始化一些变量
     */
    public static void initData() {
        SPManager.getInstance(context).put("isDialogShowing", false);
        SPManager.getInstance(context).put("dialogCount", 0);
    }

    public static void addActivity(Activity activity) {
        mActivitys.add(activity);
    }

    public static void removeActivity(Activity activity) {
        mActivitys.remove(activity);
    }

    public static boolean isAppAlive() {
        return mActivitys.size() > 0;
    }

    public static void exit() {
        try {
            for (int i = mActivitys.size() - 1; i >= 0; i--) {
                Activity activity = mActivitys.get(i);
                if (activity != null) {
                    activity.finish();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int activityAount = 0;
    ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            EbeiApplication.addActivity(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {
            if (activityAount == 0) {
                //app回到前台
                Log.i("APP重新进入前台");
                boolean isLoginOffline = SPManager.getInstance(context).get(CommonConstants.IS_LOGIN_OFFLINE, true);
                if (CommonConstants.IS_MESSAGE_OPEN && !isLoginOffline) {
                    Log.i("QQIM正在登陆");
                    QQIMUtil.getInstance().doLogin(activity, mUserAccount);
                }

                Log.i("不再接收第三方推送");
                PushUtils.stopPushService(activity);

                // 检查更新
                //checkVersionAuto(activity);
            }
            SPManager.getInstance(context).put(CommonConstants.IS_APP_FOREGROUND, true);
            activityAount++;
        }

        @Override
        public void onActivityResumed(Activity activity) {
        }
        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
            activityAount--;
            if (activityAount == 0) {
                Log.i("APP进入后台");
                SPManager.getInstance(context).put(CommonConstants.IS_APP_FOREGROUND, false);

                // 如果被挤下线过,就没有必要重连
                boolean isLoginOffline = SPManager.getInstance(context).get(CommonConstants.IS_LOGIN_OFFLINE, true);
                if (CommonConstants.IS_MESSAGE_OPEN && !isLoginOffline) {
                    Log.i("启动第三方推送");
                    PushUtils.startPushService(activity);
                }
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
        @Override
        public void onActivityDestroyed(Activity activity) {
            EbeiApplication.removeActivity(activity);
            if (!(activity instanceof DialogActivity)) {
                int count = SPManager.getInstance(activity).get("dialogCount", 0);
                if (count > 0) {
                    sendBroadcast(new Intent("ACTION_EXIT_DIALOG"));
                }
            }
        }
    };

}